package com.example.common.sendhttp;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.support.ApiException;
import com.example.common.utils.RedisUtils;
import com.example.common.vo.WxSubScribeMessageVo;
import com.example.common.vo.WxTemplateMessageVo;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Component;

import java.util.Map;

import javax.annotation.Resource;


/**
 * 发送请求到微信工具类
 *
 * @Author rlj
 * @Date 2021/3/31 20:29
 * @Version 1.0
 */
@Component
public class WxSendMessage {

    @Resource
    private RedisUtils redisUtils;

    private String appid = "";
    private String platform = "";
    /**
     * 获得指定端的accessToken
     * 患者端：patient 药师端： drug 医生端：doctor
     *
     * @param client 指定的端
     * @return 获得access_token
     */
    public String getAccessToken(String appid, String secret) {
        this.appid = appid;
        this.platform = "wx";
        return getAccessToken(appid, secret, platform);
    }

    
    private String getAccessToken(String appid, String secret, String platform) {
        if (!redisUtils.hasKey(platform + "-" + appid)) {
            return getTokenAndSave(appid, secret, platform);
        }
        return (String) redisUtils.get(platform + "-" + appid);
    }

    /**
     * 小程序发送消息
     *
     * @param wxSubScribeMessageVo 封装的消息对象
     * @param accessToken          得到的accessToken
     * @return 微信返回的json string
     */
    public boolean sendSubscribeMessage(WxSubScribeMessageVo wxSubScribeMessageVo, String accessToken) {
        try {
            String body = JSON.toJSONString(wxSubScribeMessageVo);
            String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body);
            JSONObject jsonObject = JSONObject.parseObject(post);
            if ("ok".equals(jsonObject.get("errmsg"))) {
                return true;
            } else {
                throw new ApiException(1, post);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 发送模板信息
     *
     * @param wxTemplateMessage 封装的模板信息
     * @param accessToken       得到的accessToken
     * @return ture 成功 false 失败
     */
    public boolean sendTemplate(WxTemplateMessageVo wxTemplateMessage, String accessToken) {
        String body = JSON.toJSONString(wxTemplateMessage);

        try {
            String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, body);
            JSONObject jsonObject = JSONObject.parseObject(post);
            if ("ok".equals(jsonObject.get("errmsg"))) {
                return true;
            } else {
                throw new ApiException(1, post);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String createWxaCode(String accessToken, Map<String, String> req) {
        String body = JSON.toJSONString(req);
        byte[] qrCode = null;
        try {
            qrCode = HttpRequest.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken).header(HTTP.CONTENT_TYPE, "application/json").body(body).execute().bodyBytes();
            String post=new String(qrCode);

            JSONObject jsonObject = JSONObject.parseObject(post);
            if ("ok".equals(jsonObject.get("errmsg"))) {
                return "";
            } else if (40001 == jsonObject.getIntValue("errcode")){
                // redisUtils.delete(platform + "-" + appid);
                throw new ApiException(1, post);
            } else {
                throw new ApiException(1, post);
            }
        } catch (Exception e) {     
            return Base64.encodeBase64String(qrCode);
        }
    }


    /**
     * 发送请求到微信获得access_token
     *
     * @param appId  微信申请的appId
     * @param secret 微信申请的secret
     * @return 返回微信的json字符串
     */
    private JSONObject sendHttp(String appId, String secret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        String resultString = HttpUtil.get(String.format(url, appId, secret));
        return JSONObject.parseObject(resultString);
    }


    /**
     * 发送请求到微信获得accessToke
     *
     * @param appId  微信申请的appId
     * @param secret 微信申请的secret
     * @return 返回 获得的accessToken
     */
    private String getTokenAndSave(String appId, String secret, String platform) {
        // 发送获得access_token
        JSONObject jsonObject = sendHttp(appId, secret);
        String accessToken = (String) jsonObject.get("access_token");
        int expiresIn = (int) jsonObject.get("expires_in");
        boolean set = redisUtils.set(platform + "-" + appId, accessToken, expiresIn - 60);
        if (set) {
            return accessToken;
        }
        return "";
    }

}
